package com.antler.smt.portal.service.impl;

import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.OrderConstant;
import com.antler.smt.entity.ReceivingAddressEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.ReceivingAddressEntityMapper;
import com.antler.smt.portal.mapper.ReceivingAddressInfoMapper;
import com.antler.smt.request.portal.GetReceivingAddressReq;
import com.antler.smt.response.admin.GetReceivingAddressListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.portal.ReceivingAddressService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 收货地址接口
 *
 * @author zhangyi
 * @date 2018/3/27 17:33
 */
@Service
public class ReceivingAddressServiceImpl implements ReceivingAddressService {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private ReceivingAddressInfoMapper receivingAddressInfoMapper;

    @Autowired
    private ReceivingAddressEntityMapper receivingAddressEntityMapper;

    /**
     * 获取其收获地址列表
     * @param memberId
     * @return
     */
    @Override
    public Result<GetReceivingAddressListResp> getpurchaserAddressList(long memberId) {
        Result result = null;
        List<GetReceivingAddressListResp> addressByMember = receivingAddressInfoMapper.getAddressByMember(memberId);

        //将默认地址显示在第一条上
        Collections.sort(addressByMember, new Comparator<GetReceivingAddressListResp>() {
            @Override
            public int compare(GetReceivingAddressListResp o1, GetReceivingAddressListResp o2) {
                return o2.getIsDefault() - o1.getIsDefault();
            }
        });

        //显示该用户的所有收货地址，后期在做修改
        result = new Result(addressByMember);

        return result;
    }

    /**
     * 写入收货地址
     * @param addressReq 请求实体
     * @param memberId 会员id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> writeReceivingAddress(GetReceivingAddressReq addressReq,long memberId) {

        Result result = null;
        //收货地址实体
        ReceivingAddressEntity addressEntity = new ReceivingAddressEntity();

        //添加会员id
        addressEntity.setMemberId(memberId);

        //添加国家id名字
        addressEntity.setCountryId(addressReq.getCountryId());
        addressEntity.setCountryName(addressReq.getCountryName());

        //添加省份id名字
        addressEntity.setProvinceId(addressReq.getProvinceId());
        addressEntity.setProvinceName(addressReq.getProvinceName());

        //添加城市id名字
        addressEntity.setCityId(addressReq.getCityId());
        addressEntity.setCityName(addressReq.getCityName());

        //添加详细地址
        addressEntity.setDetailaddress(addressReq.getDetailaddress());

        //添加收货人姓名
        addressEntity.setName(addressReq.getName());

        //添加邮编
        addressEntity.setPostCode(addressReq.getPostCode());

        //添加手机号
        addressEntity.setMobile(addressReq.getMobile());

        //添加电话
        addressEntity.setTelphone(addressReq.getTelphone());

        //设置地址有效性
        addressEntity.setIsInvalid(0);

        //判断是否是默认
        if(addressReq.getIsDefault() == 1){

            clearDefault(memberId);

        }

        //添加默认地址信息
        addressEntity.setIsDefault(addressReq.getIsDefault());

        //初始化时间日期
        addressEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        addressEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        List<GetReceivingAddressListResp> addressList = receivingAddressInfoMapper.getAddressByMember(memberId);

        //地址最多保存20条
        if(addressList.size()<= OrderConstant.ADRESS_SIZE){
            int insert = receivingAddressEntityMapper.insert(addressEntity);
            boolean flag = (0 == insert);
            if (flag) {
                result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
            } else {
                result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
            }
        }else{
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }
        return result;
    }

    /**
     *  查询一条收货地址
     *
     * @param id
     * @return
     */
    @Override
    public Result<GetReceivingAddressListResp> getReceivingAddress(Long id) {
        Result result = null;
        ReceivingAddressEntity addressEntity = receivingAddressEntityMapper.selectByPrimaryKey(id);
        result = new Result(addressEntity);
        return result;
    }

    /**
     *  更新收货地址
     *
     * @param addressReq 请求实体
     * @param id 收货地址id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> updateReceivingAddress(GetReceivingAddressReq addressReq, long id) {

        Result result = null;
        //创建收货地址实体
        ReceivingAddressEntity addressEntity  = new ReceivingAddressEntity();

        addressEntity.setId(id);

        //修改国家id名字
        addressEntity.setCountryId(addressReq.getCountryId());
        addressEntity.setCountryName(addressReq.getCountryName());

        //修改省份id名字
        addressEntity.setProvinceId(addressReq.getProvinceId());
        addressEntity.setProvinceName(addressReq.getProvinceName());

        //修改城市id名字
        addressEntity.setCityId(addressReq.getCityId());
        addressEntity.setCityName(addressReq.getCityName());

        //修改详细地址
        addressEntity.setDetailaddress(addressReq.getDetailaddress());

        //修改收货人姓名
        addressEntity.setName(addressReq.getName());

        //修改邮编
        addressEntity.setPostCode(addressReq.getPostCode());

        //修改手机号
        addressEntity.setMobile(addressReq.getMobile());

        //修改电话
        addressEntity.setTelphone(addressReq.getTelphone());

        if(addressReq.getIsDefault() == 1) {
            //清空默认地址
            ReceivingAddressEntity receivingAddressEntity = receivingAddressEntityMapper.selectByPrimaryKey(id);

            clearDefault(receivingAddressEntity.getMemberId());
        }

        //修改默认地址信息
        addressEntity.setIsDefault(addressReq.getIsDefault());

        //修改更新时间
        addressEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i = receivingAddressEntityMapper.updateByPrimaryKeySelective(addressEntity);

        boolean flag = (0 == i);
         if(flag){
             result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
         }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
         }
        return result;
    }

    /**
     *  删除收货地址
     *
     * @param id 会员id
     * @return
     */
    @Override
    public Result<ResultCodeEnum> delReceivingAddress(long id) {
        Result result = null;
        int i = 0;

        //创建一个地址实体
        ReceivingAddressEntity receivingAddressEntity = new ReceivingAddressEntity();
        receivingAddressEntity.setId(id);
        //将地址标志位置为无效位
        receivingAddressEntity.setIsInvalid(1);

        i = receivingAddressEntityMapper.updateByPrimaryKeySelective(receivingAddressEntity);
        boolean flag = (0 == i);
        if(flag){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     *  设置默认收货地址
     *
     * @param id
     * @return
     */
    @Override
    public Result<ResultCodeEnum> defaultReceivingAddress(long id) {
        Result result = null;

        //新建实体
        ReceivingAddressEntity receivingAddressEntity = new ReceivingAddressEntity();

        //清空默认地址
        ReceivingAddressEntity receiving = receivingAddressEntityMapper.selectByPrimaryKey(id);

        clearDefault(receiving.getMemberId());

        //设置默认地址
        receivingAddressEntity.setIsDefault(1);

        receivingAddressEntity.setId(id);

        //设置更新时间
        receivingAddressEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i = receivingAddressEntityMapper.updateByPrimaryKeySelective(receivingAddressEntity);

        boolean flag = (0 == i);
        if(flag){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     * 清空以前的默认地址
     *
     * @param memberId
     */
    public void clearDefault(Long memberId){

        //创建修改实体
        List<GetReceivingAddressListResp> addressByMember = receivingAddressInfoMapper.getAddressByMember(memberId);

        //创建修改实体
        ReceivingAddressEntity re = new ReceivingAddressEntity();

        for(GetReceivingAddressListResp addressList : addressByMember){
            //修改标志
            re.setIsDefault(0);

            //添加会员id
            re.setId(addressList.getId());

            receivingAddressEntityMapper.updateByPrimaryKeySelective(re);
        }

    }
}
